<template>
	<view class="content" :style="{backgroundColor: (searchStatus?'#FFFAFB':'#FFFFFF')}">
		<view :style="{height: (titleTop + statusBarHeight) + 'px'}">
			<!-- 占位符 -->
		</view>
		<view class="mainHeader" :style="{paddingTop: titleTop + 'px'}">
			<headNav class="headWrap" :minHeight="statusBarHeight">
				<template #titleBox>
					<view class="inputLay">
						<uni-easyinput trim="all" :styles="styles" :placeholderStyle="placeholderStyle"
							confirmType="search" @confirm="changeInputFn" primaryColor="#FF9BA7" @clear="clearInput"
							placeholder="搜索店铺或机台关键词" v-model="value1" prefixIcon="search"><!-- @blur="changeInputFn" -->
						</uni-easyinput>
					</view>
				</template>
			</headNav>
		</view>
		<template v-if="!searchStatus">
			<view class="searchWrap">
				<view class="title">
					历史搜索
				</view>
				<view class="searchLay">
					<view class="searchItem" v-for="(item,index) in searchRecordList" :key="index" v-if="index<=5">
						<view class="txt" @click="selectTxt(item.txt,index)">{{item.txt}}</view>
						<uni-icons class="closeempty" type="closeempty" color="#979797" size="12"
							@click.stop="clearItem(index)"></uni-icons>
					</view>
				</view>
			</view>
			<view class="pictureLay_none">
				<view class="topTitle">

					<view class="title">
						热门搜索
					</view>
					<view class="subTitle">
						<!-- <view class=""> -->
						店铺排行
						<!-- </view> -->
						<image src="/static/index/rankIcon.png" mode="widthFix"></image>
					</view>
				</view>
				<view class="pictureItem" v-for="(item,index) in shopListNot" :key="index"
					@click="linkUrl('/pages/index/storeDetails'+'?shopId='+item.id)">
					<cardListItem :avatar="item.avatar" :title="item.name" :cardWidth='92' :cardHeight='92'>
						<template #priceTip>
							<view class="tagLay">
								<view class="tagItem tagBg1">
									56人收藏
								</view>
								<view class="tagItem tagBg2">
									火影联动
								</view>
								<view class="tagItem tagBg3">
									34人在抽
								</view>
							</view>
						</template>
					</cardListItem>
					<view class="RankBox" v-if="index<3">
						<image v-if="index==0" class="rankIcon" src="/static/index/1icon.png" mode="widthFix"></image>
						<image v-if="index==1" class="rankIcon" src="/static/index/2icon.png" mode="widthFix"></image>
						<image v-if="index==2" class="rankIcon" src="/static/index/3icon.png" mode="widthFix"></image>
					</view>
					<view class="Ranking" v-else>
						{{index+1}}
					</view>
				</view>
			</view>
		</template>
		<template v-if="searchStatus">
			<view class="searchTitle">
				搜索到以下结果
			</view>
			<scroll-view scroll-x="true" class="nav-scroll" @scrolltolower="scrolltolower">
				<!-- 导航项容器 -->
				<view class="nav-item" v-for="(item, index) in shopList" :key="index"
					@click="linkUrl('/pages/index/storeDetails'+'?shopId='+item.id)">
					<image class="shopAvatar" mode="widthFix" :src="shopList.avatar"></image>
					<view class="shopName">{{item.name}}</view>
					<view class="tagLay">
						<view class="tagItem tagBg1">
							56人收藏
						</view>
						<!-- 	<view class="tagItem tagBg2">
									火影联动
								</view>
								<view class="tagItem tagBg3">
									34人在抽
								</view> -->
					</view>
				</view>
			</scroll-view>
			<view class="pictureLay">
				<noData v-if="machinesList.length === 0 && !loading"></noData>
				<view class="pictureItem" v-for="(item,index) in machinesList" :key="index">
					<pictureDisplay :dataItem="item" v-if="item.showtype==1"></pictureDisplay>
					<pictureDisplayTow :dataItem="item" v-else></pictureDisplayTow>
				</view>
				<!-- 使用uni-load-more组件显示加载状态 -->
				<uni-load-more :status="loading ? 'loading' : noMoreData ? 'noMore' : 'more'"
					iconType="auto"></uni-load-more>
			</view>
		</template>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				searchStatus: false, //判断用户是否进行了搜索
				shopListNot: [], //未进行搜索，出来的商铺列表
				shopList: [],
				machinesList: [],
				searchRecordList: [],
				styles: {
					backgroundColor: " #F2F2F2",
					color: '#343434',
					borderColor: '#F2F2F2',
				},
				placeholderStyle: "color:#B6B6B6;font-size:21rpx",
				value1: '',
				searchType: '', //搜索类型,all=全部,shop=店铺,machine=机台,
				page: 1, // 当前页码
				page_size: 3, // 每页数量
				total: 0, // 总数据量
				loading: false, // 是否正在加载
				noMoreData: false, // 是否没有更多数据

				page_shop: 1, // 当前页码
				page_size_shop: 10, // 每页数量
				total_shop: 0, // 总数据量
				// loading_shop: false, // 是否正在加载
				noMoreData_shop: false, // 是否没有更多数据
			};
		},
		onLoad(e) {
			this.searchRecordList = uni.getStorageSync('searchRecord') || [];
			if(e.value){
				this.value1=e.value;
				this.searchStatus=true;
				this.changeInputFn();
			}else{
				this.searchStatus=false;
				this.getHomeNoSearchFn();
			}
		},
		onHide() {
			uni.setStorageSync('searchRecord', this.searchRecordList)
		},
		onUnload() {
			uni.setStorageSync('searchRecord', this.searchRecordList)
		},
		// 触底加载更多
		onReachBottom() {
			if (!this.searchStatus) return
			// 如果没有更多数据或正在加载，则返回
			if (this.noMoreData || this.loading) return

			// 页码增加并获取下一页数据
			this.page++
			this.getHomeSearchFn('machine');
		},
		methods: {
			linkUrl(url) {
				uni.navigateTo({
					url
				})
			},
			clearInput(){
				this.searchStatus = false;
				this.getHomeNoSearchFn();
			},
			// 仅在输入框失去焦点或用户按下回车时触发	
			changeInputFn(index) {
				console.log(this.value1,index);
				if (!this.value1.trim()) {
					return
				}
				// const index = this.searchRecordList.indexOf(this.value1);
				debugger;
				if (index > -1) {
					this.searchRecordList.splice(index, 1);
				}
				this.searchRecordList.unshift({
					txt: this.value1
				})
				this.searchStatus = true;
				// 这里有点特殊进入搜索页的时候展示的是热门搜索（店铺）
				// 搜索后会出现店铺与机台两个列表，有独立的分页参数与逻辑
				this.getHomeSearchFn('shop');
				this.getHomeSearchFn('machine');
			},
			clearItem(index) {
				this.searchRecordList.splice(index, 1);
				uni.setStorageSync('searchRecord', this.searchRecordList)
			},
			selectTxt(txt,index) {
				this.value1 = txt;
				this.changeInputFn(index);
			}, 

			// 滚动到底部/右边，会触发 scrolltolower 事件
			// 店铺的
			scrolltolower: function(e) {
				console.log(e);
				// 如果没有更多数据或正在加载，则返回
				if (this.noMoreData_shop || this.loading) return

				// 页码增加并获取下一页数据
				this.page_shop++;
				this.getHomeSearchFn('shop')
			},
			//未进行搜索
			getHomeNoSearchFn() {
				this.$http('/v1/home/search', {
					type: "shop",
					keyword: '',
					page: 1,
					limit: 10,
				}).then(res => {
					console.log(res, "搜索");
					if (res.code == 0) {
						const
							data = res.data;
						this.shopListNot = data.shops.list || []
					} else {
						this.$showToast(res.msg)
					}
				})
			},
			// 搜索
			getHomeSearchFn(searchType) {
				// 防止重复请求
				if (this.loading) return;

				// 设置加载状态
				this.loading = true;
				uni.showLoading({
					title: '加载中...'
				})
				let dataField = {};
				if (searchType == 'shop') {
					dataField = {
						type: searchType,
						keyword: this.value1,
						page: this.page_shop,
						limit: this.page_size_shop,
					}
				} else {
					dataField = {
						type: searchType,
						keyword: this.value1,
						page: this.page,
						limit: this.page_size,
					}
				}
				try {
					this.$http('/v1/home/search', dataField).then(res => {
						console.log(res, "搜索");
						if (res.code == 0) {
							// this.shopList=res.data.shops
							const
								data = res.data;
							// 如果是第一页，直接赋值
							if (searchType == 'shop') {
								if (this.page_shop === 1) {
									this.shopList = data.shops.list || []

								} else {
									// 后续页，合并数据
									this.shopList = [...this.shopList, ...(data.shops.list || [])]

								}
								// 更新总数据量
								this.total_shop = data.shops.total || 0

								// 判断是否还有更多数据
								this.noMoreData_shop = this.shopList.length >= this.total_shop

							} else {
								if (this.page === 1) {
									this.machinesList = data.machines.list || []

								} else {
									// 后续页，合并数据
									this.machinesList = [...this.machinesList, ...(data.machines.list || [])]

								}
								// 更新总数据量
								this.total = data.machines.total || 0

								// 判断是否还有更多数据
								this.noMoreData = this.machinesList.length >= this.total
							};
						} else {
							this.$showToast(res.msg)
						}
					})
				} catch (error) {
					console.error('请求失败:', error)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				} finally {
					// 重置加载状态
					this.loading = false
					uni.hideLoading();
					uni.stopPullDownRefresh();
				}
			},
			// {{apiurl}}v1/home/search?type=machine&keyword=前端&page=1&limit=20
		}
	}
</script>
<style>

</style>
<style lang="scss" scoped>
	.content {
		min-height: 100vh;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.mainHeader {
		border: 2rpx solid #DDDDDD;
		background-color: #fff;
		position: fixed;
		z-index: 9;
		top: 0;

		::v-deep .inputLay {
			width: 434upx;
			// margin: 0 auto 56upx;

			.is-input-border {
				border-radius: 30upx;
			}

			.uni-easyinput__content-input {
				height: 62upx;
			}
		}
	}

	.searchWrap {
		padding-top: 44upx;
		padding-left: 80upx;
		padding-right: 66upx;

		.title {
			font-family: SourceHanSansSC, SourceHanSansSC;
			font-weight: 500;
			font-size: 32rpx;
			color: #000000;
			line-height: 48rpx;
			margin-bottom: 20upx;
		}

		.searchLay {
			@include flexLayout(center);
			flex-wrap: wrap;
			row-gap: 32upx;
			column-gap: 20rpx;

			.searchItem {
				@include flexLayout(center, space-between);
				min-width: 164rpx;
				height: 54rpx;
				background: #F2F2F2;
				border-radius: 28rpx;
				padding: 0 12upx 0 20upx;
				font-family: SourceHanSansSC, SourceHanSansSC;
				font-weight: 500;
				font-size: 22rpx;
				color: #828282;
				line-height: 1;

				.txt {
					width: 100%;
					line-height: 54rpx;
					padding-right: 26upx;
					white-space: nowrap;
				}

				.closeempty {
					width: 20upx;
					line-height: 54rpx;
					text-align: right;
				}
			}
		}
	}

	.searchTitle {
		font-family: SourceHanSansSC, SourceHanSansSC;
		font-weight: 400;
		font-size: 23upx;
		color: #A9A9A9;
		line-height: 40rpx;
		margin-top: 32upx;
		margin-left: 62upx;
	}

	.nav-scroll {
		white-space: nowrap;
		/* 防止子元素换行 */
		overflow: hidden;
		/* 隐藏超出部分 */
		-webkit-appearance: none;
		// padding-left: 78upx;
		margin-top: 20upx;
		width: calc(100% - 78upx);
		margin-left: auto;

		.nav-item {
			@include setwh(172rpx, 248rpx);
			margin-right: 40upx;
			padding: 34upx 16upx 24upx;
			display: inline-block;
			background: #FFFFFF;
			box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(190, 190, 190, 0.5);
			border-radius: 8rpx;

			.shopAvatar {
				display: block;
				@include setwh(108rpx, 108rpx);
				background-color: #F3F3F3;
				border-radius: 50%;
				margin: 12upx auto 12upx;
			}

			.shopName {
				width: 172rpx;
				display: block !important;
				@include lineOver;
				font-family: SourceHanSansSC, SourceHanSansSC;
				font-weight: 500;
				font-size: 21rpx;
				color: #000000;
			}
		}
	}

	.pictureLay {
		width: 700upx;
		margin: 80upx auto;

		.pictureItem {
			margin-bottom: 40upx;
			position: relative;
		}
	}

	.pictureLay_none {
		width: 646upx;
		margin: 60upx auto;
		border-radius: 38rpx;
		padding: 20upx 26upx;
		position: relative;
		overflow: hidden;

		&:before {
			position: absolute;
			// z-index: -1;
			content: '';
			top: 0;
			left: 0;
			right: 0;
			height: 626rpx;
			background: linear-gradient(180deg, #FBDCE6 0%, rgba(255, 235, 235, 0) 100%);
		}

		.topTitle {
			@include flexLayout(center, space-between);
			margin-bottom: 50upx;
			position: relative;
			z-index: 1;

			.title {
				font-family: SourceHanSansSC, SourceHanSansSC;
				font-weight: 500;
				font-size: 32rpx;
				color: #000000;
				line-height: 48rpx;
			}

			.subTitle {
				font-weight: 300;
				font-size: 22rpx;
				color: #929292;
				line-height: 22rpx;
				@include flexLayout(flex-end, center);

				image {
					width: 26rpx;
					height: 0;
					margin-left: 6upx;
				}
			}
		}

		::v-deep .pictureItem {
			margin-bottom: 66upx;
			position: relative;
			padding-left: 12upx;
			position: relative;

			.RankBox {
				position: absolute;
				top: -12upx;
				left: 4upx;

				.rankIcon {
					width: 30rpx;
					height: 28rpx;
				}
			}

			.Ranking {
				position: absolute;
				top: -4upx;
				left: 4upx;
				width: 22rpx;
				height: 22rpx;
				border-radius: 50%;
				text-align: center;
				line-height: 24upx;
				background: #000000;
				font-family: AlimamaShuHeiTi, AlimamaShuHeiTi;
				font-weight: bold;
				font-size: 14rpx;
				color: #FFFFFF;
			}

			.itemBox {
				border-bottom: none;

				.priceTxt {
					display: none;
				}
			}


		}
	}

	.tagLay {
		margin-top: 16upx;
		@include flexLayout(center);
		flex-wrap: wrap;
		row-gap: 12upx;
		column-gap: 12rpx;

		.tagItem {
			min-width: 78rpx;
			height: 28rpx;
			line-height: 28upx;
			border-radius: 4rpx;
			padding: 0 12upx;
			font-size: 12rpx;
			text-align: center;
		}

		.tagBg1 {
			background: #FFDEED;
			color: #F36BA9;
		}

		.tagBg2 {
			background: #FFDABB;
			color: #FF7400;
		}

		.tagBg3 {
			background: #DDF9ED;
			color: #18D081;
		}
	}
</style>